<template>
	<div class="layout-padding">
		<splitpanes @resize="handleResize">
			<pane class="!overflow-scroll">
				<div>
					<el-card>
						<el-form :model="form" label-width="80px" ref="formRef" size="small" :rules="dataRules">
							<el-row :gutter="12">
								<el-col :span="6" class="mb20">
									<el-form-item prop="siteId" label="区域">
										<el-select v-model="form.siteId" @change="handleChangeSite" filterable>
											<el-option v-for="item in siteList" :key="item.id" :label="item.name" :value="item.id"></el-option>
										</el-select>
									</el-form-item>
								</el-col>

								<el-col :span="6" class="mb20">
									<el-form-item prop="monitorEquipmentId" label="设备">
										<el-select v-model="form.monitorEquipmentId" @change="handleChangeEquipment" filterable>
											<el-option v-for="item in equitpmentList" :key="item.id" :label="item.name" :value="item.id"></el-option>
										</el-select>
									</el-form-item>
								</el-col>

								<el-col :span="6" class="mb20">
									<el-form-item prop="factorIdList" label="检测因子">
										<el-select v-model="form.factorIdList" multiple collapse-tags collapse-tags-tooltip>
											<el-option v-for="item in divisorList" :key="item.id" :label="item.cnName" :value="item.id"></el-option>
										</el-select>
									</el-form-item>
								</el-col>

								<el-col :span="6" class="mb20">
									<el-form-item prop="type" label="数据类型">
										<el-select v-model="form.type">
											<el-option v-for="item in rangeType" :key="item.name" :label="item.label" :value="item.name"></el-option>
										</el-select>
									</el-form-item>
								</el-col>

								<el-col :span="10" class="mb20">
									<el-form-item prop="dateTime" label="起止时间">
										<el-date-picker
											class="ml-1"
											v-model="form.dateTime"
											type="datetimerange"
											start-placeholder="开始时间"
											end-placeholder="结束时间"
											value-format="YYYY-MM-DD HH:mm:ss"
										/>
									</el-form-item>
								</el-col>
								<el-col :span="6" class="mb20">
									<el-tooltip effect="light" placement="right">
										<span>
											<el-button icon="search" type="primary" @click="handleSubmit" :loading="state.loading">查询</el-button>
											<span class="ml-1 text-error">
												<el-icon><WarningFilled /></el-icon>
											</span>
										</span>
										<template #content>
											<div class="text-error">当前版本只支持查询{{ dataPeriod }}天的数据。</div>
										</template>
									</el-tooltip>
									<!-- <el-button type="info">导出</el-button> -->
								</el-col>
							</el-row>
						</el-form>
						<div class="w-full h-[420px] min-h-[420px]">
							<LineChartHistory
								:seriesData="chartProps.seriesData"
								:xAxisData="chartProps.xAxisData"
								:divisor="chartProps.divisor"
								ref="LineChartHistoryRef"
							/>
						</div>
					</el-card>
					<el-card class="mt-2">
						<el-table :data="state.dataList" size="small" height="420px" :loading="state.loading">
							<el-table-column type="index" width="60" label="序号" v-if="tableColumns.length" align="center" />
							<el-table-column label="采集时间" prop="recordTime" width="180" v-if="tableColumns.length" show-overflow-tooltip align="center">
								<template #default="{ row }">
									{{ parseTime(row.recordTime, '') }}
								</template>
							</el-table-column>
							<el-table-column
								v-for="item in tableColumns"
								:key="item.id"
								:label="item.cnName"
								:prop="item.columnName"
								min-width="80"
								align="center"
							/>
						</el-table>

						<pagination
							:small="true"
							@size-change="sizeChangeHandle"
							:disabled="state.loading"
							@current-change="currentChangeHandle"
							v-bind="state.pagination"
						/>
					</el-card>
				</div>
			</pane>
			<pane class="ml8" size="30">
				<div class="layout-padding-auto layout-padding-view">
					<el-card header="设备信息">
						<div>
							<div class="mb-2">设备名称：{{ mapMarkerSite?.name }}</div>
							<div class="mb-2">设备编码：{{ mapMarkerSite?.equipmentCode }}</div>
							<div class="mb-2">
								设备状态：<el-tag v-show="form.monitorEquipmentId" :type="mapMarkerSite?.status === 2 ? 'success' : 'danger'">{{
									mapMarkerSite?.status === 2 ? '在线' : '离线'
								}}</el-tag>
							</div>
						</div>
					</el-card>
					<el-card header="地图位置" class="mt-4">
						<div ref="amapRef" class="w-full h-[400px]"></div>
					</el-card>
				</div>
			</pane>
		</splitpanes>
	</div>
</template>

<script setup lang="ts" name="dataMgmtHistory">
import { formatDate } from '/@/utils/formatTime';
import { fetchHistoricalData } from '/@/api/platform/dataTemplate';
import { fetchListAll as fetchSiteList } from '/@/api/platform/airSite';
import { fetchListAll as fetchEquipmentList } from '/@/api/platform/airMonitorEquipment';
import { fetchFactorDetailList as fetchDataTemplateList } from '/@/api/platform/dataTemplate';
import { rangeType } from './data';
import { parseTime } from '/@/utils/formatTime';
import { useRoute } from 'vue-router';
import { useScript } from '/@/hooks/web/useScript';
import { useMessage } from '/@/hooks/message';
import { getObj } from '/@/api/admin/tenant';
import { Session } from '/@/utils/storage';

const LineChartHistory = defineAsyncComponent(() => import('./components/lineChart.vue'));
const A_MAP_URL = 'https://webapi.amap.com/maps?v=2.0&key=999fec27d4e861c0c34fb4e8d5fdb948';
const amapRef = ref();
const { toPromise } = useScript({ src: A_MAP_URL });
const LineChartHistoryRef = ref();
const route = useRoute();
const formRef = ref();
const dataPeriod = ref(0);
const form: any = reactive({
	siteId: '',
	monitorEquipmentId: '',
	factorIdList: [],
	type: 'RealTime',
	dateTime: [formatDate(new Date(new Date().getTime() - 3600 * 1000 * 24), 'YYYY-mm-dd HH:MM:SS'), formatDate(new Date(), 'YYYY-mm-dd HH:MM:SS')],
});
const mapMarkerSite = reactive({
	latitude: '',
	longitude: '',
	name: '',
	equipmentCode: '',
	status: null,
});
const siteList: any = ref([]);
const divisorList: any = ref([]);
const equitpmentList: any = ref([]);
const tableData: any = ref([]);
const tableColumns: any = ref([]);
//  table pagination props
const state = reactive({
	dataList: [],
	loading: false,
	pagination: {
		total: 0,
		size: 10,
		current: 1,
	},
});
// charts data
const chartProps = reactive({
	divisor: [],
	xAxisData: [],
	seriesData: [],
});
let map: any;
let AMap: any;
let marker: any;
async function initMap() {
	await toPromise();
	await nextTick();
	const wrapEl = unref(amapRef);
	if (!wrapEl) return;
	AMap = (window as any).AMap;
	map = new AMap.Map(wrapEl, {
		resizeEnable: true,
	});
	if (mapMarkerSite.latitude && mapMarkerSite.longitude) {
		const ct = new AMap.LngLat(mapMarkerSite.longitude, mapMarkerSite.latitude);
		map.setZoomAndCenter(14, ct);
	}
	marker = new AMap.Marker({
		clickable: true,
		position: [mapMarkerSite.longitude, mapMarkerSite.latitude],
	});
	marker.setMap(map);
}
const handleMarkerPos = (location: { longitude: number; latitude: number }) => {
	const ct = new AMap.LngLat(location.longitude, location.latitude);
	if (!marker) {
		marker = new AMap.Marker({
			clickable: false,
			position: ct,
		});
		marker.setMap(map);
	}
	marker.setPosition(ct);
	map.setCenter(ct);
};
// 获取租户套餐信息
const getTenantInfo = () => {
	const id = Session.getTenant();
	getObj(id).then((res) => {
		dataPeriod.value = res.data.dataPeriod;
	});
};
getTenantInfo();
const getDataList = async () => {
	state.loading = true;
	try {
		const res = await fetchHistoricalData({
			dt0: form.dateTime[0],
			dt1: form.dateTime[1],
			tp: form.type,
			monitorEquipmentId: form.monitorEquipmentId,
			factorIdList: form.factorIdList,
		});
		if (res.data.length) {
			const cols: any = form.factorIdList.map((d: any) => {
				const item = divisorList.value.find((k: any) => k.id === d);
				// 对象键转，因子英文名统一转换成小写，匹配列表props值
				let table_data_key = item.enName.toLowerCase();
				return Object.assign(item, { columnName: table_data_key });
			});
			tableColumns.value = cols;
			tableData.value = res.data;
			state.pagination.total = res.data.length;
			getPageData();
			const time: any = res.data.map((d: any) => parseTime(d.recordTime, ''));
			const chartVal: any = [];
			for (let i = 0; i < cols.length; i++) {
				const chartVal_item = [];
				for (let k = 0; k < res.data.length; k++) {
					const item = res.data[k];
					const v = item[cols[i].columnName];
					chartVal_item.push(v);
				}
				const s = {
					data: chartVal_item,
					name: cols[i]?.cnName,
					// encode: { x: 'recordTime' },
					connectNulls: false,
					type: 'line',
					smooth: true,
					symbol: 'circle',
					symbolSize: [6, 6],
					showSymbol: false,
					lineStyle: { width: 1 },
				};
				chartVal.push(s);
			}
			chartProps.divisor = cols;
			chartProps.xAxisData = time;
			chartProps.seriesData = chartVal;
		} else {
			tableColumns.value = [];
			tableData.value = [];
			state.dataList = [];
			state.pagination = {
				total: 0,
				size: 10,
				current: 1,
			};
			chartProps.divisor = [];
			chartProps.xAxisData = [];
			chartProps.seriesData = [];
		}
		state.loading = false;
	} catch (err) {
		useMessage().error(err.msg);
	} finally {
		state.loading = false;
	}
};
const getPageData = () => {
	const l = tableData.value.slice((state.pagination.current - 1) * state.pagination.size, state.pagination.current * state.pagination.size);
	state.dataList = l;
};
const sizeChangeHandle = (val: number) => {
	state.pagination.size = val;
	getPageData();
};
const currentChangeHandle = (val: number) => {
	state.pagination.current = val;
	getPageData();
};
const getSites = async () => {
	const res = await fetchSiteList();
	siteList.value = res.data;
};
const getDivisor = async (dataTemplateId: string) => {
	const res = await fetchDataTemplateList({ id: dataTemplateId });
	const l = res.data[0];
	l && (divisorList.value = res.data);
};
const getEquipment = async (siteId: string) => {
	form.monitorEquipmentId = '';
	const res = await fetchEquipmentList({ airSiteId: siteId });
	equitpmentList.value = res.data;
};
const handleResize = () => {
	unref(LineChartHistoryRef).resizeFnPollute();
};
const handleMapMarker = (site: any) => {
	const location = {
		longitude: site.longitude,
		latitude: site.latitude,
	};
	handleMarkerPos(location);
};
const handleChangeSite = (e: any) => {
	getEquipment(e);
};
const handleChangeEquipment = async (e: any) => {
	form.factorIdList = [];
	const item = equitpmentList.value.find((d: any) => d.id === e);
	if (!item) return;
	Object.assign(mapMarkerSite, item);
	await getDivisor(item.dataTemplateId);
	nextTick(() => {
		handleMapMarker(item);
	});
};
// 定义校验规则
const dataRules = ref({
	siteId: [{ required: true, message: '请选择', trigger: 'change' }],
	monitorEquipmentId: [{ required: true, message: '请选择', trigger: 'change' }],
	factorIdList: [{ required: true, message: '请选择', trigger: 'change' }],
	type: [{ required: true, message: '请选择', trigger: 'change' }],
	dateTime: [{ required: true, message: '请选择', trigger: 'change' }],
});
// 查询
const handleSubmit = async () => {
	const valid = await formRef.value.validate();
	if (!valid) return false;
	getDataList();
};
onMounted(async () => {
	await initMap();
	await getSites();
	await nextTick(async () => {
		const q: any = route.query;
		if (q?.siteId) {
			await getEquipment(q.siteId);
			await handleChangeEquipment(q.monitorEquipmentId);
			form.factorIdList = [q.factorId];
			form.monitorEquipmentId = q.monitorEquipmentId;
			form.siteId = q.siteId;
			form.dateTime = [q.dateTime, q.dateTime];
			await getDataList();
		}
	});
});
</script>

<style lang="scss" scoped>
:deep(.amap-logo) {
	display: none !important;
}
:deep(.amap-copyright) {
	display: none !important;
}
</style>
